﻿using System.Collections.Generic;
using System.Collections;
using UnityEngine;

namespace Jinndev {

    public class MapGridRenderer : MonoBehaviour {

        public static readonly float DefalutAngle = 26.6f;
        public static readonly float DefalutLength = 40f;
        public static readonly float DefalutScale = 1f;
        public static readonly int DefalutCount = 50;

        public Material material;

        [Tooltip("线段夹角")]
        [Range(10, 80)]
        public float angle = DefalutAngle;

        [Tooltip("线段长度")]
        [Range(10, 500)]
        public float length = DefalutLength;

        [Tooltip("缩放")]
        [Range(0.2f, 10)]
        public float scale = DefalutScale;

        [Tooltip("数量")]
        [Range(10, 1000)]
        public int sizeX = DefalutCount;

        [Tooltip("数量")]
        [Range(10, 1000)]
        public int sizeY = DefalutCount;

        [Tooltip("中心点位置")]
        public Vector2 centerOffset = new Vector2();

        // OnPostRender 在UGUI下面画， OnGUI 在UGUI上面画
        // 用RenderTexture时，需要OnPostRender
        private void OnPostRender() {
            if (!material) {
                return;
            }
            //设置该材质通道，0为默认值
            material.SetPass(0);
            //设置绘制2D图像
            GL.LoadOrtho();
            //表示开始绘制，绘制类型为线段
            GL.Begin(GL.LINES);

            float x = length * scale * Mathf.Cos(angle * Mathf.Deg2Rad);
            float y = length * scale * Mathf.Sin(angle * Mathf.Deg2Rad);

            {
                Vector2 start = new Vector2(0, 0);
                Vector2 end = new Vector2(x, y);
                Vector2 half = (end - start) / 2 * sizeY;

                for (int i = -sizeX / 2; i <= sizeX / 2; i++) {
                    DrawLine(-half, half, new Vector2(x * i, -y * i));
                }
            }

            {
                Vector2 start = new Vector2(0, 0);
                Vector2 end = new Vector2(x, -y);
                Vector2 half = (end - start) / 2 * sizeX;

                for (int i = -sizeY / 2; i <= sizeY / 2; i++) {
                    DrawLine(-half, half, new Vector2(x * i, y * i));
                }
            }

            //结束绘制
            GL.End();
        }

        private void DrawLine(Vector2 start, Vector2 end, Vector2 offset) {
            Vector2 half = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f); // 不能在Awake和Start中缓存，因为会变
            DrawLine(half + centerOffset + start + offset, half + centerOffset + end + offset);
        }

        private void DrawLine(Vector2 start, Vector2 end) {
            //绘制线段，需要将屏幕中某个点的像素坐标除以屏幕宽或高
            GL.Vertex(new Vector3(start.x / Screen.width, start.y / Screen.height, 0));
            GL.Vertex(new Vector3(end.x / Screen.width, end.y / Screen.height, 0));
        }

    }

}
